﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

/// <summary>
/// Summary description for MsgUtils
/// </summary>
public class MsgUtils
{
   // Fields
    private string filename;
    private XmlDocument xmlDoc;

    // Methods
    public MsgUtils()
    {
        this.xmlDoc = null;
    }

    public MsgUtils(string filename)
    {
        this.xmlDoc = null;
        this.filename = filename;
    }

    public string GetError(string code, string defaultValue)
    {
        if (this.XmlDoc.FirstChild == null)
        {
            throw new Exception("Invalid Error Xml File.");
        }
        foreach (XmlNode node in this.XmlDoc.FirstChild.ChildNodes)
        {
            if (((node.NodeType != XmlNodeType.Comment) && (node.Attributes.Count > 1)) && (node.Attributes[0].Value == code))
            {
                return node.Attributes[1].Value;
            }
        }
        return defaultValue;
    }

    // Properties
    public string FileName
    {
        set
        {
            this.filename = value;
            if (this.xmlDoc != null)
            {
                try
                {
                    this.xmlDoc.Load(this.filename);
                }
                catch
                {
                }
            }
        }
    }

    public string this[string code]
    {
        get
        {
            if (this.XmlDoc.FirstChild == null)
            {
                throw new Exception("Invalid Error Xml File.");
            }
            foreach (XmlNode node in this.XmlDoc.FirstChild.ChildNodes)
            {
                if (((node.NodeType != XmlNodeType.Comment) && (node.Attributes.Count > 1)) && (node.Attributes[0].Value == code))
                {
                    return node.Attributes[1].Value;
                }
            }
            throw new Exception("Not found error code: " + code);
        }
    }

    public XmlDocument XmlDoc
    {
        get
        {
            if (this.xmlDoc == null)
            {
                this.xmlDoc = new XmlDocument();
                this.xmlDoc.Load(this.filename);
            }
            return this.xmlDoc;
        }
    }
}
